package com.example.administrator.social.util;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.example.administrator.social.R;
import com.example.administrator.social.model.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018/9/10 0010.
 */

public class AllenUtils {
        private static  long timeFlag = 0;
        private static  int  view_id = 0;
        private static Toast toast;

        public static int dp2px(Context context, float dp)
        {
            return (int ) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
        }

        /**
         * 获得屏幕宽度
         *
         * @param context
         * @return
         */
        public static int getScreenWidth(Context context)
        {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE );
            DisplayMetrics outMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(outMetrics);
            return outMetrics .widthPixels ;
        }
        public static void setActionBarColor(Window window, Activity activity, int color){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // 透明状态栏
                window.addFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                // 透明导航栏
                window.addFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                SystemStatusManager tintManager = new SystemStatusManager(activity);
                tintManager.setStatusBarTintEnabled(true);
                // 设置状态栏的颜色
                tintManager.setStatusBarTintResource(color);
                window.getDecorView().setFitsSystemWindows(true);
        }
    }



    // 根据年月日计算年龄,birthTimeString:"1994-11-14"
    public static int getAgeFromBirthTime(Date date) {
        // 得到当前时间的年、月、日
        if (date!=null){
            Calendar cal = Calendar.getInstance();
            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH) + 1;
            int dayNow = cal.get(Calendar.DATE);
            //得到输入时间的年，月，日
            cal.setTime(date);
            int selectYear = cal.get(Calendar.YEAR);
            int selectMonth = cal.get(Calendar.MONTH) + 1;
            int selectDay =cal.get(Calendar.DATE);
            // 用当前年月日减去生日年月日
            int yearMinus = yearNow - selectYear;
            int monthMinus = monthNow - selectMonth;
            int dayMinus = dayNow - selectDay;
            int age = yearMinus;// 先大致赋值
            if (yearMinus <=0) {
                age = 0;
            }if (monthMinus < 0) {
                age=age-1;
            } else if (monthMinus == 0) {
                if (dayMinus < 0) {
                    age=age-1;
                }
            }
            return age;
        }
        return 0;
    }

    // strTime要转换的string类型的时间，formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒，
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType){
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 验证是否为手机号码
     * @param mobiles
     * @return
     */
    public static boolean isMobile(String mobiles) {
        Pattern p = Pattern .compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 是否合格的email
     * @param mobiles
     * @return
     */
    public static boolean isEmail(String mobiles) {
        Pattern p = Pattern .compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$" );
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * "^^[a-zA-Z0-9]{6,20}+$"  密码：以字母开头，长度在6~18之间，只能包含字母、数字和下划线
     * @param mobiles
     * @return
     */
    public static boolean isPasswordOk(String mobiles) {
        Pattern p = Pattern .compile("^[a-zA-Z0-9]{6,20}+$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * "^[A-Za-z0-9]{3,20}+$
     * 判断用户名是否合格 帐号是否合法(字母开头，允许5-16字节，允许字母数字下划线)
     */
    public static boolean isUserName(String mobiles) {
        Pattern p = Pattern .compile("^[A-Za-z0-9]{3,20}+$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 昵称：长度1到20
     * @param mobiles
     * @return
     */
    public static boolean isNickNameOk(String mobiles) {
        Pattern p = Pattern .compile("^.{1,20}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }


    public static String getResourcesUri(Context context,@DrawableRes int id) {
        Resources resources = context.getResources();
        String uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(id) + "/" +
                resources.getResourceTypeName(id) + "/" +
                resources.getResourceEntryName(id);
        return uriPath;
    }


    /**
     * 获取当前用户名
     */
    public static String getUserName(Context context){
        SharedPreferences preferences = context.getSharedPreferences("user", Context.MODE_PRIVATE);
        return preferences.getString("name", "");
    }


    /**
     * 是否频繁的点击按钮
     * @param id：点击的控件  time:点击时的时间
     * @return
     */
    public static boolean isFrequentClick(Context context,int id,long time){
        if(id==view_id&&view_id!=0){
            if(timeFlag-time<=1000){
                return false;
            }else{
                showToast(context,context.getResources().getString(R.string.you_click__frequent));
                return true;
            }
        }
        timeFlag = time;
        return false;
    }

    public static void showToast(Context context,
                                 String content) {
        if (toast == null) {
            toast = Toast.makeText(context,
                    content,
                    Toast.LENGTH_SHORT);
        } else {
            toast.setText(content);
        }
        toast.show();
    }

    public static String getCurTime(String style){
        SimpleDateFormat format = new SimpleDateFormat(style);
       return format.format(System.currentTimeMillis());
    }

    public static String getDateFormat(long time,String style){
        SimpleDateFormat format = new SimpleDateFormat(style);
        return format.format(time);
    }
    public static User getSharedPreferencesObjData(Context context, String preferenceName, String key) {
        SharedPreferences sharedPreferences=context.getSharedPreferences(preferenceName,context.MODE_PRIVATE);
        String temp = sharedPreferences.getString(key, "");
        ByteArrayInputStream bais =  new ByteArrayInputStream(Base64.decode(temp.getBytes(), Base64.DEFAULT));
        User user = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(bais);
            user = (User) ois.readObject();
        } catch (IOException e) {
        }catch(ClassNotFoundException e1) {

        }
        return user;
    }

    public static void saveSharedPreferencesObjData(Context context, String preferenceName,String key,User user){
        if(user instanceof Serializable) {
            SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceName, context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(user);//把对象写到流里
                String temp = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
                editor.putString(key, temp);
                editor.commit();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                throw new Exception("User must implements Serializable");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
